#include <QCoreApplication>
#include <QCommandLineParser>
#include <QDebug>

#include "lisserver.h"
#include "sigwatch.h"
#include "logger.h"

int main(int argc, char *argv[])
{
    qInstallMessageHandler(Logger::log);
    QCoreApplication app(argc, argv);

    QCommandLineParser parser;
    parser.setApplicationDescription("LIS Server Simualtor");
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption port({"p","port"}, "serial port name", "ttyS0");
    parser.addOption(port);

    parser.process(app);
    QString portName;
    if(parser.isSet(port)) {
        portName = parser.value("port");
    }

    LISServer server(portName);

    if(!server.isOpen()) {
        return -1;
    }

    UnixSignalWatcher sigwatch;
    sigwatch.watchForSignal(SIGINT);
    sigwatch.watchForSignal(SIGTERM);
    sigwatch.watchForSignal(SIGQUIT);
    QObject::connect(&sigwatch, &UnixSignalWatcher::unixSignal, &app, [&](int){
        qDebug() << "exit by signal";
        server.close();
        app.quit();
    });

    return app.exec();
}
